#!/bin/sh -e

#    This file is part of Ec2-on-Rails.
#    http://code.google.com/p/ec2-on-rails/
#
#    Copyright 2007 Paul Dowman, http://pauldowman.com/
#
#    Ec2-on-Rails is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    Ec2-on-Rails is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.


#
# This is the init script to start/stop mongrel
#

NAME="mongrel cluster"
NO_START=0

start_cmd() {
    sudo -u app /usr/local/ec2-on-rails/bin/mongrel_cluster_ctl_wrapper start
    return $?
}

stop_cmd() {
    sudo -u app /usr/local/ec2-on-rails/bin/mongrel_cluster_ctl_wrapper stop
    return $?
}


########################################

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/var/lib/gems/1.8/bin

. /lib/lsb/init-functions

test -f /etc/default/rcS && . /etc/default/rcS

if [ "$NO_START" != "0" -a "$1" != "stop" ]; then 
        [ "$VERBOSE" != no ] && log_warning_msg "Not starting $NAME - edit $0 and change NO_START to be 0.";
        exit 0;
fi

case "$1" in
    start)
        log_begin_msg "Starting $NAME..."
        if start_cmd; then
                log_end_msg 0
        else
                log_end_msg 1
        fi
    ;;
    stop)
        log_begin_msg "Stopping $NAME..."
        if stop_cmd; then
                log_end_msg 0
        else
                log_end_msg 1
        fi
    ;;
    restart)
        log_begin_msg "Restarting $NAME..."
        if ! stop_cmd; then
                log_end_msg 1
        fi
        sleep 10
        if start_cmd; then
                log_end_msg 0
        else
                log_end_msg 1
        fi
    ;;
    *)
        log_success_msg "Usage: $0 {start|stop|restart}"
    ;;
esac